package net.zoneland.knowledge.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期转化.
 * @author zx
 */
public class DateConverter implements Converter<Date> {

    /**
     * 系统默认所在时区
     */
    private static final ZoneId zone = ZoneId.systemDefault();

    /**
     * 格式化时间，yyyy年MM月dd日
     */
    private static final DateTimeFormatter df = DateTimeFormatter.ofPattern(DateHelper.CHINA_DATE_FORMAT_STR);

    @Override
    public Class<?> supportJavaTypeKey() {
        return Converter.super.supportJavaTypeKey();
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return Converter.super.supportExcelTypeKey();
    }

    /**
     * 导出excel内容时，对data进行转化为yyyy年MM月dd日.
     * @param value 需要转化的col.
     * @param contentProperty
     * @param globalConfiguration
     * @return
     */
    @Override
    public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        final String time = value.toInstant()
                .atZone(zone)
                .toLocalDateTime()
                .format(df);
        return new WriteCellData<>(time);
    }
}
